package com.diudiutechnology.www.yadiudiu.yadiudiu.mine.MyActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.diudiutechnology.www.yadiudiu.R;
import com.diudiutechnology.www.yadiudiu.util.http.HttpClient;
import com.diudiutechnology.www.yadiudiu.util.http.JsonTools;
import com.diudiutechnology.www.yadiudiu.util.utils.Constant;
import com.diudiutechnology.www.yadiudiu.util.utils.ImgUtils;
import com.diudiutechnology.www.yadiudiu.util.utils.MyProgressDialog;
import com.diudiutechnology.www.yadiudiu.util.utils.PermissionsChecker;
import com.diudiutechnology.www.yadiudiu.util.utils.PictureUtil;
import com.diudiutechnology.www.yadiudiu.util.utils.SelectPhotoPop;
import com.diudiutechnology.www.yadiudiu.util.utils.Sundry;
import com.diudiutechnology.www.yadiudiu.util.utils.ToastUtils;
import com.diudiutechnology.www.yadiudiu.util.utils.UserInfoUtils;
import com.diudiutechnology.www.yadiudiu.util.view.UniversalPhotoPop;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyActivity.BaseActivity;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyActivity.LoginActivity;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyApplication;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.CommodityManagementModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.MerchantsTypeModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.MineFragmentModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.UniversalModel;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Created by Administrator on 2017/9/2.
 * 添加购车 商品
 */

public class AddCarPurchasesGoodsActivity extends BaseActivity implements View.OnClickListener, Callback.CommonCallback<String> {
    @Bind(R.id.retur)
    LinearLayout retur;

    @Bind(R.id.title_center)
    TextView title_center;

    @Bind(R.id.button)//提交
            Button button;

    @Bind(R.id.labelling_layout)//标签
            LinearLayout labelling_layout;
    @Bind(R.id.labelling_text)//标签文字
            TextView labelling_text;

    @Bind(R.id.manufacture_date_layout)//日期
            LinearLayout manufacture_date_layout;
    @Bind(R.id.manufacture_date_text)//日期文字
            TextView manufacture_date_text;

    @Bind(R.id.posted_layout)//广告图
            RelativeLayout posted_layout;
    @Bind(R.id.modificon_img)//广告首图
            ImageView modificon_img;
    @Bind(R.id.modification)//广告图
            RelativeLayout modification;
    @Bind(R.id.modification_text)//广告图文字
            TextView modification_text;

    @Bind(R.id.rent_way_text)//提车地区
            RelativeLayout rent_way_text;
    @Bind(R.id.please_select_address)//地区
            TextView please_select_address;

    @Bind(R.id.goods_name)//商品名称
            EditText goods_name;
    @Bind(R.id.guideprice)//指导价
            EditText guideprice;
    @Bind(R.id.sellingprice)//销售价
            EditText sellingprice;
    @Bind(R.id.carcolor)//汽车颜色
            EditText carcolor;

    @Bind(R.id.customerservice)//汽车售后
            EditText customerservice;

    @Bind(R.id.travel)//行驶公里
            EditText travel;

    Context context;

    String pos = "0"; //0、添加商品  1、修改商品 2、展示商品
    String u_id = "";//商家ID  pos=0时 u_id 为店铺id   pos=1时 u_id 为商品id  pos=2时 u_id 为商品id
    String merchanttype = "";//类型
    String typeid = "";//类型id
    String addimg = "";//图片
    String posted = "";//图片集合
    String detailsa = "";
    private MyProgressDialog mDialog;
    String Judge_interface = "0";//判断哪个接口   0、获取类型 1、上传图片 2、上传
    int Judge_img = 0;//图片是否点击 和 类型是否点击
    List<UniversalModel> getclasstype = new ArrayList<>();//分类
    boolean Judge = false;
    private View viewkre;
    private SelectPhotoPop selectPhotoPop;
    private DisplayImageOptions options;
    private ImageLoader imageLoader;
    List<CommodityManagementModel> buycarlist = new ArrayList<>();
    int ints = 0;
    int arrive_year, arrive_month, arrive_day;
    String province = "";//省
    String city = "";// 市
    String area = "";//  区
    String longitude = "";//   经度
    String latitude = "";//  纬度

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewkre = View.inflate(this, R.layout.activity_add_car_purchases_goods, null);
        setContentView(viewkre);
        ButterKnife.bind(this);
        context = this;
        initView();
    }

    private void initView() {
        retur.setOnClickListener(this);
        labelling_layout.setOnClickListener(this);
        manufacture_date_layout.setOnClickListener(this);
        posted_layout.setOnClickListener(this);
        modificon_img.setOnClickListener(this);
        rent_way_text.setOnClickListener(this);
        button.setOnClickListener(this);
        MineFragmentModel mineFragmentModel = UserInfoUtils.readUserInfo(this);
        merchanttype = mineFragmentModel.getMerchanttype();

        options = ImgUtils.imageOptions();
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(context));
        if (getIntent() != null) {
            pos = getIntent().getStringExtra("pos");
            u_id = getIntent().getStringExtra("id");
            if (!pos.equals("0")) {
                ints = getIntent().getIntExtra("ints", 0);
                buycarlist = (List<CommodityManagementModel>) getIntent().getSerializableExtra("data");
            }
        }
        if (pos.equals("1")) {
            title_center.setText("修改商品");
            button.setText("修改");
            processdetails();
        } else if (pos.equals("2")) {
            title_center.setText("商品详情");
            button.setVisibility(View.GONE);
            processdetails();
            Judge_img = 1;
            processnNotEdit();
        }
        if (!pos.equals("2")) {
            processclasstype();
        }

    }

    //展示产品详情
    private void processdetails() {
        if (buycarlist != null && buycarlist.size() > 0) {
            CommodityManagementModel ManagementModel = buycarlist.get(ints);
//            goods_name.setText(ManagementModel.getName());
//            introduction.setText(ManagementModel.getIntroduction());
//            classification.setText(ManagementModel.getNametype());
//            commodity_prices.setText(ManagementModel.getPrice());
//            addimg = ManagementModel.getImg();
//            typeid = ManagementModel.getClassid();
//            imageLoader.displayImage(Constant.HTTP + addimg, add, options);
        }
    }

    //不可编辑
    public void processnNotEdit() {
//        goods_name.setEnabled(false);
//        introduction.setEnabled(false);
//        commodity_prices.setEnabled(false);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.retur:
                finish();
                break;
            case R.id.labelling_layout://标签选择
                if (Judge_img == 0) {
                    if (getclasstype.size() > 0) {
                        processtype();
                    } else {
                        Judge = true;
                        processclasstype();
                    }
                }
                break;
            case R.id.manufacture_date_layout://日期选择
                if (Judge_img == 0) {
                    getdiareqi();
                }
                break;
            case R.id.modificon_img://选择图片
                if (Judge_img == 0) {
                    Intent intent = new Intent(context, GeneralPictureEditorActivity.class);
                    intent.putExtra("pos", "0");
                    intent.putExtra("Judge_posstr", "1");
                    intent.putExtra("conumg", posted);
                    startActivityForResult(intent, Constant.ADDCARIMG);
                }
                break;
            case R.id.rent_way_text://选择地址
                if (Judge_img == 0) {
                    Intent intent = new Intent(context, SelectTheAddressActivity.class);
                    intent.putExtra("pos", "4");
                    startActivityForResult(intent, Constant.ADDADDRESSCARIMG);
                }
                break;
            case R.id.button://提交商品
//                if (TextUtils.isEmpty(goods_name.getText().toString().trim())) {//商品名称
//                    ToastUtils.show(context, getResources().getString(R.string.please_product_name));
//                    return;
//                }
//                if (TextUtils.isEmpty(introduction.getText().toString().trim())) {//商品简介
//                    ToastUtils.show(context, getResources().getString(R.string.please_introduction));
//                    return;
//                }
//                if (TextUtils.isEmpty(classification.getText().toString().trim())) {//商品分类
//                    ToastUtils.show(context, getResources().getString(R.string.please_classification));
//                    return;
//                }
//                if (TextUtils.isEmpty(commodity_prices.getText().toString().trim())) {//商品价格
//                    ToastUtils.show(context, getResources().getString(R.string.please_price));
//                    return;
//                }
//                if (TextUtils.isEmpty(addimg)) {//商品图片
//                    ToastUtils.show(context, getResources().getString(R.string.please_add));
//                    return;
//                }
                processupload();
                break;
            case R.id.posted_layout://添加照片
                if (Judge_img == 0) {
                    if (!PermissionsChecker.getPermissionsChecker(this, "0", 0)) {
                        if (!PermissionsChecker.getPermissionsChecker(this, "0", 2)) {
                            showSelectPicPop();
                        } else {
                            ToastUtils.show(context, "请检查是否打开储存权限");
                        }
                    } else {
                        ToastUtils.show(context, "请检查是否打开相机权限");
                    }
                }
                break;
                          /* 注释  相机*/
            case R.id.item_popupwindows_camera:
                selectPhotoPop.dismiss();
                GalleryFinal.openCamera(Constant.CAMERA, MyApplication.getInstance().initGalley(Constant.CAMERA, 1), mOnHanlderResultCallback);
                break;
            /* 注释  相册*/
            case R.id.item_popupwindows_Photo:
                selectPhotoPop.dismiss();
                GalleryFinal.openGallerySingle(Constant.GALLERYSINGLE, MyApplication.getInstance().initGalley(Constant.GALLERYSINGLE, 1), mOnHanlderResultCallback);
                break;
            /* 注释  取消*/
            case R.id.item_popupwindows_cancel:
                selectPhotoPop.dismiss();
                break;

        }
    }

    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            Bitmap bitmap = PictureUtil.decodeSampledBitmapFromFile(resultList.get(0).getPhotoPath(), Constant.WIDE, Constant.WIDE);
            String conimg = PictureUtil.saveBitmapFile(bitmap, String.valueOf(0));

            Intent intent = new Intent(context, GeneralPictureEditorActivity.class);
            intent.putExtra("pos", "0");
            intent.putExtra("Judge_posstr", "0");
            intent.putExtra("conumg", conimg);
            startActivityForResult(intent, Constant.ADDCARIMG);
            processupload(conimg);
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("stringmd5=" + requestCode + "resultCode=" + resultCode);


        if (resultCode == Constant.ADDCARIMG) {

            posted = data.getStringExtra("posted");//图片集合
            String conumg = data.getStringExtra("conumg");// 首图
            String number = data.getStringExtra("number");// 首图
            if (TextUtils.isEmpty(posted)) {
                posted_layout.setVisibility(View.VISIBLE);
                modification.setVisibility(View.GONE);
            } else {
                posted_layout.setVisibility(View.GONE);
                modification.setVisibility(View.VISIBLE);
                imageLoader.displayImage(Constant.HTTP + conumg, modificon_img, options);
                modification_text.setText("编辑图片(" + number + "/6)");
            }
        } else if (resultCode == Constant.ADDADDRESSCARIMG) {
            please_select_address.setText(data.getStringExtra("address"));
            province = data.getStringExtra("province");//省
            city = data.getStringExtra("city");// 市
            area = data.getStringExtra("district");//  区
            longitude = data.getStringExtra("longitude");//   经度
            latitude = data.getStringExtra("latitude");//  纬度

        }
    }

    //相册
    private void showSelectPicPop() {
        selectPhotoPop = new SelectPhotoPop(this, this);
        selectPhotoPop.showAtLocation(viewkre, Gravity.BOTTOM, 0, 0);
    }

    //绑定标签
    private void processtype() {
        UniversalPhotoPop typephoto = new UniversalPhotoPop(context, getclasstype, 1);
        typephoto.showAtLocation(viewkre, Gravity.BOTTOM, 0, 0);
        typephoto.setAddresskListener(new UniversalPhotoPop.OnAddressCListener() {
            @Override
            public void onClick(String provinces, String citys, String areas) {
                labelling_text.setText(provinces);
                for (int i = 0; i < getclasstype.size(); i++) {
                    if (provinces.equals(getclasstype.get(i).getName())) {
                        typeid = getclasstype.get(i).getId();
                    }
                }
            }
        });
    }

    public void getdiareqi() {
        final AlertDialog alert = new AlertDialog.Builder(context)
                .create();
        alert.show();
        Window window = alert.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.dimAmount = 0.5f;
        window.setGravity(Gravity.CENTER);
//        window.setLayout(Utils.getScreenWidth(context),
//                Utils.getScreenHeight(context));
        window.setContentView(R.layout.date_time_picker);

        final DatePicker datePicker = (DatePicker) window.findViewById(R.id.new_act_date_picker);

        TextView que = (TextView) window.findViewById(R.id.queren);
        TextView quxiao = (TextView) window.findViewById(R.id.quxiao);
        TextView qingkong = (TextView) window.findViewById(R.id.qingkong);
        final int year;
        final int month;
        final int day;

        final Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);

        datePicker.init(year, month, day, null);

        que.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                arrive_year = datePicker.getYear();
                arrive_month = datePicker.getMonth();
                arrive_day = datePicker.getDayOfMonth();

                String months = "01";
                String days = "01";
                if ((arrive_month + 1) < 10) {
                    months = "0" + (arrive_month + 1);
                } else {
                    months = "" + (arrive_month + 1);
                }
                if (arrive_day < 10) {
                    days = "0" + arrive_day;
                } else {
                    days = "" + arrive_day;
                }

                if (arrive_year > year) {
                    ToastUtils.show(context, getResources().getString(R.string.please_cannot_date));
                    alert.dismiss();
                    return;
                }
                System.out.println("stringmd5result==arrive_month===" + arrive_month + "=month=" + month);
                if (arrive_month > month) {
                    ToastUtils.show(context, getResources().getString(R.string.please_cannot_date));
                    alert.dismiss();
                    return;
                }
                if (arrive_month == month) {
                    if (arrive_day > day) {
                        ToastUtils.show(context, getResources().getString(R.string.please_cannot_date));
                        alert.dismiss();
                        return;
                    }
                }

                manufacture_date_text.setText(arrive_year + "-" + months + "-" + days);
                alert.dismiss();

            }
        });
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alert.dismiss();
            }
        });
        qingkong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                manufacture_date_text.setText("");

                alert.dismiss();
            }
        });

    }

    //商品分类
    private void processclasstype() {
        if (Sundry.isOpenNetwork(context)) {

            mDialog = new MyProgressDialog(context);
            Judge_interface = "0";


            HttpClient.classtype(Constant.CARBUYINGTYPE, this);
        } else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }

    //上传图片
    private void processupload(String upload) {
        if (Sundry.isOpenNetwork(context)) {
            Judge_interface = "1";
            mDialog = new MyProgressDialog(context);
            HttpClient.upload(upload, this);
        } else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }

    //商品上传
    private void processupload() {
        if (Sundry.isOpenNetwork(context)) {
            mDialog = new MyProgressDialog(context);
            Judge_interface = "2";
            String data = "";

            if (pos.equals("0")) {//产品上传
                data = Constant.CARBUYINGUPLOAD;
            } else {
                data = Constant.CARBUYINGUPDATE;//产品修改
            }


            HttpClient.CarBuying(data, pos, u_id, posted, goods_name.getText().toString().trim(),
                    labelling_text.getText().toString().trim(), guideprice.getText().toString().trim(), sellingprice.getText().toString().trim(),
                    carcolor.getText().toString().trim(), customerservice.getText().toString().trim(), travel.getText().toString().trim(),
                    manufacture_date_text.getText().toString().trim(), please_select_address.getText().toString().trim(), detailsa,
                    province, city, area, longitude, latitude, this);
        } else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }


    @Override
    public void onSuccess(String result) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        System.out.println("stringmd5result" + result);
        List<MerchantsTypeModel> getnote = JsonTools.getmerchanttype(result);
        if (getnote != null || getnote.size() > 0) {
            String error = getnote.get(0).getError();
            String mssage = getnote.get(0).getMssage();
            if (error.equals("200")) {
                String content = getnote.get(0).getResult();
                if (Judge_interface.equals("0")) {//商品分类
                    getclasstype = JsonTools.getclasstype(content);
                    if (Judge) {
                        processtype();
                    }
                } else if (Judge_interface.equals("1")) {//图片
                    addimg = content;
                    // imageLoader.displayImage(Constant.HTTP + content, add, options);
                } else if (Judge_interface.equals("2")) {//上传修改
                    finish();
                    ToastUtils.show(context, mssage);
                }
            } else if (error.equals("105")) {
                Intent intent = new Intent(context, LoginActivity.class);
                startActivity(intent);
                ToastUtils.show(context, mssage);
            } else {
                ToastUtils.show(context, mssage);
            }
        }
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        ToastUtils.Toastshow(context, getResources().getString(R.string.server));
    }

    @Override
    public void onCancelled(CancelledException cex) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        ToastUtils.Toastshow(context, getResources().getString(R.string.server));
    }

    @Override
    public void onFinished() {

    }
}

